<template>
  <a-modal title="提交审批" :visible="show" @ok="handleOk" @cancel="handleCancel" width="600px" :maskClosable="false">
    <div>
      <a-form-model ref="mainForm" :model="flow" style="display: flex; flex-direction: column" :label-col="labelCol"
        :wrapper-col="wrapperCol">
        <a-form-model-item label="申请人">
          <a-select show-search :value="flow.applyUser" :default-active-first-option="false" :show-arrow="false"
            :filter-option="false" :not-found-content="null" @search="fetchUserList"
            @focus="clickPersonSelector('applyUser', '0')" @change="selectUserList" disabled>
            <a-select-option v-for="d in personList" :key="'new_' + d.username">
              {{ d.realname }}({{ d.username }})
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="项目负责人">
          <a-select show-search :value="flow.projectHeader" :default-active-first-option="false" :show-arrow="false"
            :filter-option="false" :not-found-content="null" @search="fetchUserList"
            @focus="clickPersonSelector('projectHeader', '0')" @change="selectUserList">
            <a-select-option v-for="d in personList" :key="'new_' + d.username">
              {{ d.realname }}({{ d.username }})
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="项目经理">
          <a-select show-search v-model="flow.projectManager" :default-active-first-option="false" :show-arrow="false"
            :filter-option="false" :not-found-content="null" @search="fetchUserList"
            @focus="clickPersonSelector('projectManager', '0')" @change="selectUserList">
            <a-select-option v-for="d in personList" :key="'new_' + d.username">
              {{ d.realname }}({{ d.username }})
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <!-- <a-form-model-item label="合同跟进主管">
          <a-select show-search :value="flow.followHeader" :default-active-first-option="false" :show-arrow="false"
            :filter-option="false" :not-found-content="null" @search="fetchUserList"
            @focus="clickPersonSelector('followHeader', '0')" @change="selectUserList">
            <a-select-option v-for="d in personList" :key="'new_' + d.username">
              {{ d.realname }}({{ d.username }})
            </a-select-option>
          </a-select>
        </a-form-model-item> -->
        <!-- <a-form-model-item label="合同跟进">
          <a-select
            show-search
            :value="flow.followUser"
            :default-active-first-option="false"
            :show-arrow="false"
            :filter-option="false"
            :not-found-content="null"
            @search="fetchUserList"
            @focus="clickPersonSelector('followUser', '0')"
            @change="selectUserList"
          >
            <a-select-option v-for="d in personList" :key="'new_' + d.username">
              {{ d.realname }}({{ d.username }})
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="合同签订人">
          <a-select
            show-search
            :value="flow.signUser"
            :default-active-first-option="false"
            :show-arrow="false"
            :filter-option="false"
            :not-found-content="null"
            @search="fetchUserList"
            @focus="clickPersonSelector('signUser', '0')"
            @change="selectUserList"
          >
            <a-select-option v-for="d in personList" :key="'new_' + d.username">
              {{ d.realname }}({{ d.username }})
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="合同部门主管">
          <a-select
            show-search
            :value="flow.signHeader"
            :default-active-first-option="false"
            :show-arrow="false"
            :filter-option="false"
            :not-found-content="null"
            @search="fetchUserList"
            @focus="clickPersonSelector('signHeader', '0')"
            @change="selectUserList"
          >
            <a-select-option v-for="d in personList" :key="'new_' + d.username">
              {{ d.realname }}({{ d.username }})
            </a-select-option>
          </a-select>
        </a-form-model-item> -->
      </a-form-model>
    </div>
    <UserSelector :show="showUserSelector" :muti="muti" @selected="selectUser" />
  </a-modal>
</template>

<script>
import { getAction, postAction } from '@/api/manage'
import UserSelector from '@/views/workReport/role/UserSelector'
export default {
  components: {
    UserSelector,
  },
  props: {
    show: {
      type: Boolean,
      default: false,
    },
    busKey: {
      type: String,
      default: '0',
    },
    taskDefKey: {
      type: String,
      default: null,
    },
  },
  data() {
    return {
      flow: {},
      urls: {
        flow: '/workReport/quality/flow/info',
        flowEdit: '/workReport/quality/flow/edit',
        personList: '/person/info/personList',
      },
      labelCol: { span: 6 },
      wrapperCol: { span: 18 },
      currentSelection: [],
      selectedRowKeys: [],
      muti: false,
      userSelectType: '',
      showUserSelector: false,
      personList: [],
      personMap: [],
      existPersonMap: {},
      currentType: '',
      mutil: '0',
      disableBtn: false,
      selectUserKeyWord: null,
      selectUserTimeOut: null
    }
  },
  mounted() { },
  methods: {
    fetchFlow() {
      if (this.busKey != '-1') {
        getAction(this.urls.flow + '/' + this.busKey, {}).then((res) => {
          if (res.success) {
            this.flow = res.result
            if (this.flow) {
              this.$set(this.existPersonMap, this.flow.applyUser, this.flow.applyUserId)
              this.$set(this.existPersonMap, this.flow.proDeptManager, this.flow.proDeptManagerId)
              this.$set(this.existPersonMap, this.flow.proManager, this.flow.proManagerId)
              this.$set(this.existPersonMap, this.flow.followUser, this.flow.followUserId)
              if (this.flow.userDeptUserId) {
                let userDeptUser = this.flow.userDeptUser.split(',')
                let userDeptUserId = this.flow.userDeptUserId.split(',')
                for (let i = 0; i < userDeptUser.length; i++) {
                  this.$set(this.existPersonMap, userDeptUser[i], userDeptUserId[i])
                }
              }
              if (this.flow.keepDeptUserId) {
                let keepDeptUser = this.flow.keepDeptUser.split(',')
                let keepDeptUserId = this.flow.keepDeptUserId.split(',')
                for (let i = 0; i < keepDeptUser.length; i++) {
                  this.$set(this.existPersonMap, keepDeptUser[i], keepDeptUserId[i])
                }
              }
              this.$set(this.existPersonMap, this.flow.costDeptUser, this.flow.costDeptUserId)
              this.$set(this.existPersonMap, this.flow.budgetUser, this.flow.budgetUserId)
              this.$set(this.existPersonMap, this.flow.budgetDeptHead, this.flow.budgetDeptHeadId)
              this.$set(this.existPersonMap, this.flow.purchaseDeptUser, this.flow.purchaseDeptUserId)
              this.$set(this.existPersonMap, this.flow.contractSignManager, this.flow.contractSignManagerId)
              this.$set(this.existPersonMap, this.flow.deptHeader, this.flow.deptHeaderId)
              this.$set(this.existPersonMap, this.flow.postUser, this.flow.postUserId)
              this.$set(this.existPersonMap, this.flow.settlementUser, this.flow.settlementUserId)
            }
          } else {
            this.$messageWorkReport.error(res.message)
          }
        })
      }
    },
    handleCancel() {
      this.$emit('close')
    },
    handleOk() {
      if (!this.flow.projectManager) {
        return this.$messageWorkReport.warning('请选择项目经理')
      }
      if (!this.flow.followHeader) {
        return this.$messageWorkReport.warning('请选择合同跟进主管')
      }
      // if (!this.flow.followUser) {
      //   return this.$messageWorkReport.warning('请选择合同跟进人')
      // }
      // if (!this.flow.signUser) {
      //   return this.$messageWorkReport.warning('请选择签订人')
      // }
      // if (!this.flow.signHeader) {
      //   return this.$messageWorkReport.warning('请选择合同部门主管')
      // }
      if (this.disableBtn) {
        return
      }
      this.disableBtn = true
      if (!this.taskDefKey) {
        postAction(this.urls.flowEdit, this.flow).then((res) => {
          if (res.success) {
            this.$messageWorkReport.success("提交成功");
            this.$router.go(0)
          } else {
            this.$messageWorkReport.error(res.message)
          }
          this.disableBtn = false
        })
        this.$emit('submitFlowForm')
      } else {
        this.$emit('reSelectUser', this.flow)
        this.handleCancel()
      }
    },
    openUserSelector(type, muti) {
      this.muti = muti
      this.userSelectType = type
      this.showUserSelector = true
    },
    selectUser(selection) {
      if (selection && selection.length > 0) {
        let userName = []
        let realName = []
        let userNameExits = ',' + this.flow[this.userSelectType + 'Id'] + ','
        if (this.muti) {
          selection.forEach((user) => {
            if (userNameExits.indexOf(',' + user.username.trim() + ',')) {
              userName.push(user.username.trim())
              realName.push(user.realname.trim())
            }
          })
          this.$set(
            this.flow,
            this.userSelectType + 'Id',
            this.flow[this.userSelectType + 'Id']
              ? this.flow[this.userSelectType + 'Id'] + ',' + userName.join(',')
              : userName.join(',')
          )
          this.$set(
            this.flow,
            this.userSelectType,
            this.flow[this.userSelectType]
              ? this.flow[this.userSelectType] + ',' + realName.join(',')
              : realName.join(',')
          )
        } else {
          this.$set(this.flow, this.userSelectType + 'Id', selection[0].username.trim())
          this.$set(this.flow, this.userSelectType, selection[0].realname.trim())
        }
      }
      this.showUserSelector = false
    },
    removeUser(rowIndex, type) {
      let realName = this.flow[type].split(',')
      let userName = this.flow[type + 'Id'].split(',')
      realName.splice(rowIndex, 1)
      userName.splice(rowIndex, 1)
      this.$set(this.flow, type + 'Id', userName.join(','))
      this.$set(this.flow, type, realName.join(','))
    },
    clickPersonSelector(type, mutil) {
      this.currentType = type
      this.mutil = mutil
      let usernames = this.custom[type + 'Id'] ? this.custom[type + 'Id'].split(",") : []
      let realnames = this.custom[type] ? this.custom[type].split(",") : []
      for (let i = 0; i < realnames.length; i++) {
        this.$set(this.existPersonMap, realnames[i], usernames[i])
      }
    },

    fetchUserList(value) {
      if (this.selectUserTimeOut) {
        window.clearTimeout(this.selectUserTimeOut)
      }
      this.selectUserTimeOut = window.setTimeout(this.toFetchUserList, 800)
      this.selectUserKeyWord = value
    },
    async toFetchUserList(value) {
      let param = {}
      param.keyword = this.selectUserKeyWord
      param.pageSize = 100
      let res = await postAction(this.urls.personList, param)
      if (res.success) {
        this.personList = res.result.records
        this.personList.forEach((p) => {
          this.$set(this.personMap, p.username, p.realname)
        })
      }
    },
    selectUserList(selected) {
      if (this.mutil == '1') {
        let usernames = []
        let realnames = []
        selected.forEach((s) => {
          if (s.indexOf('new_') > -1) {
            let username = s.split('_')[1]
            if (usernames.indexOf(username) <= -1) {
              usernames.push(username)
              realnames.push(this.personMap[username])
            }
          } else {
            let username = this.existPersonMap[s]
            if (usernames.indexOf(username) <= -1) {
              usernames.push(username)
              realnames.push(s)
            }
          }
        })
        this.$set(this.flow, this.currentType + 'Id', usernames.join(','))
        this.$set(this.flow, this.currentType, realnames.join(','))
      } else {
        if (selected.indexOf('new_') > -1) {
          let username = selected.split('_')[1]
          this.$set(this.flow, this.currentType + 'Id', username)
          this.$set(this.flow, this.currentType, this.personMap[username])
        } else {
          this.$set(this.flow, this.currentType + 'Id', selected)
          this.$set(this.flow, this.currentType, this.existPersonMap[selected])
        }
      }
    },
  },
  watch: {
    show(newV, oldV) {
      if (newV) {
        this.fetchFlow()
      }
    }
  },
}
</script>
<style scoped>
/deep/.ant-form .ant-row .ant-form-item-label {
  text-align: right;
  vertical-align: middle;
}

/deep/.ant-form .ant-row .ant-form-item-label {
  width: 130px !important;
}

/deep/form .ant-select {
  width: 80% !important
}

.userTag {
  padding: 5px 10px;
  margin: 2px;
  border: 1px solid #ccc;
  background-color: white;
  border-radius: 3px;
  line-height: 20px;
  display: inline-block;
}

.userTag:hover {
  padding: 5px 10px;
  margin: 2px;
  border: 1px solid #ccc;
  background-color: white;
  border-radius: 3px;
  line-height: 20px;
  color: red;
  display: inline-block;
}

.removeUserTag {
  margin-right: 0px;
  cursor: pointer;
}
</style> 
